package kitty.main.db;

import java.sql.SQLException;
import java.util.ArrayList;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class DataManager {
	
	private String[] allColumns = new String[]{SqlHelper.HIGHSCORE_NAME_COLUMN_NAME, 
			SqlHelper.HIGHSCORE_SCORE_COLUMN_NAME, SqlHelper.HIGHSCORE_DATETIME_COLUMN_NAME};

	private static Context context;
	private SqlHelper DBHelper;
	private SQLiteDatabase db;
	private ArrayList<HighScore> highScores;
	HighScore highScore;

	public DataManager(Context ctx){
		this.context = ctx;
		DBHelper = new SqlHelper(context);
	}
	public DataManager open() throws SQLException{
		db = DBHelper.getWritableDatabase();
		return this;
	}
	public void close(){
		DBHelper.close();
	}
	public long insertHighScore(HighScore newHighScore){
		ContentValues initialValues = new ContentValues();
		initialValues.put(SqlHelper.HIGHSCORE_DATETIME_COLUMN_NAME , newHighScore.getDatetime());
		initialValues.put(SqlHelper.HIGHSCORE_NAME_COLUMN_NAME, newHighScore.getName());
		initialValues.put(SqlHelper.HIGHSCORE_SCORE_COLUMN_NAME , newHighScore.getScore());
		return db.insert(SqlHelper.HIGHSCORE_TABLE_NAME, null, initialValues);
	}

	public ArrayList<HighScore> getAllHighScores() {
		highScores = new ArrayList<HighScore>();

		Cursor cursor = db.query(SqlHelper.HIGHSCORE_TABLE_NAME,
				allColumns, null, null, null, null, SqlHelper.HIGHSCORE_SCORE_COLUMN_NAME + " DESC", null);

		cursor.moveToFirst();
		while (!cursor.isAfterLast()) {
			highScore = new HighScore();
			highScore.setDatetime(cursor.getLong(2));
			highScore.setScore(cursor.getInt(1));
			highScore.setName(cursor.getString(0));
			highScores.add(highScore);
			cursor.moveToNext();
		}
		cursor.close();
		return highScores;
	}
}
